import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { VoiceVo, KnowledgeBaseListVO } from '@/api/generated/data-contracts'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from './auth'

export const useResourceStore = defineStore('resource', () => {
  // 状态
  const voices = ref<VoiceVo[]>([])
  const knowledgeBases = ref<KnowledgeBaseListVO[]>([])
  const defaultKnowledgeBases = ref<KnowledgeBaseListVO[]>([])
  const voicesLoading = ref(false)
  const knowledgeBasesLoading = ref(false)
  const defaultKnowledgeBasesLoading = ref(false)
  const voicesLastFetch = ref<number>(0)
  const knowledgeBasesLastFetch = ref<number>(0)
  const defaultKnowledgeBasesLastFetch = ref<number>(0)
  // 添加当前用户ID跟踪，用于缓存隔离
  const currentUserId = ref<string>('')

  // API实例
  const api = new Codewin({
    baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
  })



  // 计算属性
  const voicesMap = computed(() => {
    const map = new Map<string, VoiceVo>()
    voices.value.forEach(voice => {
      if (voice.id) {
        map.set(String(voice.id), voice)
      }
    })
    return map
  })

  const knowledgeBasesMap = computed(() => {
    const map = new Map<string, KnowledgeBaseListVO>()
    knowledgeBases.value.forEach(kb => {
      if (kb.id) {
        map.set(String(kb.id), kb)
      }
    })
    return map
  })

  const defaultKnowledgeBasesMap = computed(() => {
    const map = new Map<string, KnowledgeBaseListVO>()
    defaultKnowledgeBases.value.forEach(kb => {
      if (kb.id) {
        map.set(String(kb.id), kb)
      }
    })
    return map
  })

  // 合并所有知识库的计算属性，对相同ID进行去重，优先保留默认知识库
  const allKnowledgeBases = computed(() => {
    const kbMap = new Map<string, KnowledgeBaseListVO>()
    
    // 先添加普通知识库
    knowledgeBases.value.forEach(kb => {
      if (kb.id) {
        kbMap.set(String(kb.id), kb)
      }
    })
    
    // 再添加默认知识库，如果ID相同则覆盖普通知识库
    defaultKnowledgeBases.value.forEach(kb => {
      if (kb.id) {
        kbMap.set(String(kb.id), kb)
      }
    })
    
    // 转换为数组，默认知识库在前
    return Array.from(kbMap.values()).sort((a, b) => {
      // 默认知识库排在前面
      const aIsDefault = a.isDefault === 1 ? 1 : 0
      const bIsDefault = b.isDefault === 1 ? 1 : 0
      return bIsDefault - aIsDefault
    })
  })

  const allKnowledgeBasesMap = computed(() => {
    const map = new Map<string, KnowledgeBaseListVO>()
    allKnowledgeBases.value.forEach(kb => {
      if (kb.id) {
        map.set(String(kb.id), kb)
      }
    })
    return map
  })

  // 获取认证头
  const getAuthHeaders = () => {
    const authStore = useAuthStore()
    return authStore.token ? { Authorization: `Bearer ${authStore.token}` } : {}
  }

  // 检查是否需要刷新数据（5分钟缓存）
  const shouldRefreshVoices = () => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 如果用户切换了，需要重新加载
    if (currentUserId.value !== userId) {
      return true
    }
    
    return Date.now() - voicesLastFetch.value > 5 * 60 * 1000 || voices.value.length === 0
  }

  const shouldRefreshKnowledgeBases = () => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 如果用户切换了，需要重新加载
    if (currentUserId.value !== userId) {
      return true
    }
    
    return Date.now() - knowledgeBasesLastFetch.value > 5 * 60 * 1000 || knowledgeBases.value.length === 0
  }

  const shouldRefreshDefaultKnowledgeBases = () => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 如果用户切换了，需要重新加载
    if (currentUserId.value !== userId) {
      return true
    }
    
    return Date.now() - defaultKnowledgeBasesLastFetch.value > 5 * 60 * 1000 || defaultKnowledgeBases.value.length === 0
  }

  // 获取音色列表
  const fetchVoices = async (force = false) => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 检查用户是否切换，如果切换则清空缓存并更新用户ID
    if (currentUserId.value !== userId) {
      clearCache()
      currentUserId.value = userId
    }

    if (!force && !shouldRefreshVoices()) {
      return voices.value
    }

    if (voicesLoading.value) {
      return voices.value
    }

    try {
      voicesLoading.value = true
      const response = await api.request({
        path: '/codewin/voice/list',
        method: 'GET',
        query: {
          pageNo: 1,
          pageSize: 100
        },
        headers: getAuthHeaders(),
        secure: true
      })

      if (response.data?.code === 0 && response.data.data?.list) {
        voices.value = response.data.data.list
        voicesLastFetch.value = Date.now()
        console.log('音色列表加载成功:', voices.value.length, '个音色')
      } else {
        console.error('获取音色列表失败:', response.data?.message)
      }
    } catch (error) {
      console.error('获取音色列表失败:', error)
      throw error
    } finally {
      voicesLoading.value = false
    }

    return voices.value
  }

  // 获取知识库列表
  const fetchKnowledgeBases = async (force = false) => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 检查用户是否切换，如果切换则清空缓存并更新用户ID
    if (currentUserId.value !== userId) {
      clearCache()
      currentUserId.value = userId
    }

    if (!force && !shouldRefreshKnowledgeBases()) {
      return knowledgeBases.value
    }

    if (knowledgeBasesLoading.value) {
      return knowledgeBases.value
    }

    try {
      knowledgeBasesLoading.value = true
      const response = await api.getKnowledgeBaseList(
        {
          pageNo: 1,
          pageSize: 100
        },
        {
          headers: getAuthHeaders()
        }
      )

      if (response.data?.code === 0 && response.data.data?.list) {
        knowledgeBases.value = response.data.data.list
        knowledgeBasesLastFetch.value = Date.now()
        console.log('知识库列表加载成功:', knowledgeBases.value.length, '个知识库')
      } else {
        console.error('获取知识库列表失败:', response.data?.message)
      }
    } catch (error) {
      console.error('获取知识库列表失败:', error)
      throw error
    } finally {
      knowledgeBasesLoading.value = false
    }

    return knowledgeBases.value
  }

  // 获取默认知识库列表
  const fetchDefaultKnowledgeBases = async (force = false) => {
    const authStore = useAuthStore()
    const userId = authStore.userInfo?.userId || ''
    
    // 检查用户是否切换，如果切换则清空缓存并更新用户ID
    if (currentUserId.value !== userId) {
      clearCache()
      currentUserId.value = userId
    }

    if (!force && !shouldRefreshDefaultKnowledgeBases()) {
      return defaultKnowledgeBases.value
    }

    if (defaultKnowledgeBasesLoading.value) {
      return defaultKnowledgeBases.value
    }

    try {
      defaultKnowledgeBasesLoading.value = true
      const response = await api.getDefaultKnowledgeBaseList(
        {
          pageNo: 1,
          pageSize: 100
        },
        {
          headers: getAuthHeaders()
        }
      )

      if (response.data?.code === 0 && response.data.data?.list) {
        // 为默认知识库添加isDefault标识
        defaultKnowledgeBases.value = response.data.data.list.map(kb => ({
          ...kb,
          isDefault: 1 // 1表示默认知识库
        }))
        defaultKnowledgeBasesLastFetch.value = Date.now()
        console.log('默认知识库列表加载成功:', defaultKnowledgeBases.value.length, '个默认知识库')
      } else {
        console.error('获取默认知识库列表失败:', response.data?.message)
      }
    } catch (error) {
      console.error('获取默认知识库列表失败:', error)
      throw error
    } finally {
      defaultKnowledgeBasesLoading.value = false
    }

    return defaultKnowledgeBases.value
  }

  // 根据ID获取音色信息
  const getVoiceById = (voiceId: string | number): VoiceVo | undefined => {
    return voicesMap.value.get(String(voiceId))
  }

  // 根据ID获取知识库信息
  const getKnowledgeBaseById = (knowledgeId: string | number): KnowledgeBaseListVO | undefined => {
    return knowledgeBasesMap.value.get(String(knowledgeId))
  }

  // 获取音色名称
  const getVoiceName = (voiceId: string | number): string => {
    const voice = getVoiceById(voiceId)
    return voice?.voiceName || `音色-${voiceId}`
  }

  // 获取知识库名称
  const getKnowledgeBaseName = (knowledgeId: string | number): string => {
    // 首先在普通知识库中查找
    const kb = getKnowledgeBaseById(knowledgeId)
    if (kb) {
      return kb.name || `知识库-${knowledgeId}`
    }
    
    // 如果普通知识库中找不到，则在所有知识库（包含默认知识库）中查找
    const allKb = allKnowledgeBasesMap.value.get(String(knowledgeId))
    return allKb?.name || `知识库-${knowledgeId}`
  }

  // 刷新所有数据
  const refreshAll = async () => {
    await Promise.all([
      fetchVoices(true),
      fetchKnowledgeBases(true),
      fetchDefaultKnowledgeBases(true)
    ])
  }

  // 清空缓存
  const clearCache = () => {
    voices.value = []
    knowledgeBases.value = []
    defaultKnowledgeBases.value = []
    voicesLastFetch.value = 0
    knowledgeBasesLastFetch.value = 0
    defaultKnowledgeBasesLastFetch.value = 0
    // 清空当前用户ID，强制重新检查
    currentUserId.value = ''
  }

  // 初始化
  const initResource = async () => {
    // 并行加载音色和知识库数据
    try {
      await Promise.all([
        fetchVoices(),
        fetchKnowledgeBases()
      ])
    } catch (error) {
      console.error('初始化资源数据失败:', error)
    }
  }

  return {
    // 状态
    voices,
    knowledgeBases,
    defaultKnowledgeBases,
    voicesLoading,
    knowledgeBasesLoading,
    defaultKnowledgeBasesLoading,
    currentUserId,
    
    // 计算属性
    voicesMap,
    knowledgeBasesMap,
    defaultKnowledgeBasesMap,
    allKnowledgeBases,
    allKnowledgeBasesMap,
    
    // 方法
    fetchVoices,
    fetchKnowledgeBases,
    fetchDefaultKnowledgeBases,
    getVoiceById,
    getKnowledgeBaseById,
    getVoiceName,
    getKnowledgeBaseName,
    refreshAll,
    clearCache,
    initResource
  }
}, {
  persist: {
    key: 'resource-store',
    storage: localStorage,
    pick: ['voices', 'knowledgeBases', 'defaultKnowledgeBases', 'voicesLastFetch', 'knowledgeBasesLastFetch', 'defaultKnowledgeBasesLastFetch', 'currentUserId']
  }
})